package com.zzyl.nursing.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 入住Service业务层处理
 * 
 * @author kangdi
 * @date 2025-05-18
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private IBedService bedService;
    @Autowired
    private IElderService elderService;
    @Autowired
    private IContractService contractService;
    @Autowired
    private ICheckInService checkInService;
    @Autowired
    private ICheckInConfigService checkInConfigService;

    /**
     * 申请入住
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto dto) {

        String cardNumber = dto.getCheckInElderDto().getIdCardNo();//老人身份证号
        Long badId = dto.getCheckInConfigDto().getBedId(); //床位id


        //1.判断老人是否已入住  select count(*) from check_in where id_card_on =? and status =0
        Long countCheckIn = this.lambdaQuery().eq(CheckIn::getIdCardNo, cardNumber).eq(CheckIn::getStatus, 0).count();
        if(countCheckIn>0){
            throw new RuntimeException("老人已经入住了");
        }

        //2.判断符合要求的床位是否已存在  select * from bed where id=? and bad_status=0
        Bed bed = bedService.lambdaQuery()//这里查出床的所有属性，后面还要使用里面的床号和床位id
                .eq(Bed::getId, badId)
                .eq(Bed::getBedStatus, 0)
                .one();
        if(bed==null){
            throw new RuntimeException("床位已经有人");
        }

        //3.更新床位状态为 已入住 update bed set bed_status=1 where id=?
        Bed bedDB= new Bed();
        bedDB.setId(badId);
        bedDB.setBedStatus(1);//已入住
        boolean bedResult = bedService.updateById(bedDB);
        if(!bedResult){
            throw new RuntimeException("更新床位失败");
        }


        //4.新增 或 更新老人 （根据身份证号查询老人信息[select * from elder where id_card_no = ?]，有就是更新老人，没有就是创建老人）
        Elder elder = elderService.lambdaQuery().eq(Elder::getIdCardNo, cardNumber).one();
        if(elder==null){//没有就新建老人
            elder = new Elder();
        }
        //拷贝老人，如果第一次来，直接拷贝，如果之前来过，覆盖
        BeanUtils.copyProperties(dto.getCheckInElderDto(),elder);
        //观察后发现前端传进来的缺少 【床号 ，床位id，老人状态】需要自己设置
        elder.setBedId(badId);
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(4);
        boolean resultElder = elderService.save(elder);
        if (!resultElder){
            throw new RuntimeException("新增老人失败");
        }


        //5.新增签约信息（合同）
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(),contract);
        contract.setElderId(elder.getId());//老人id
        contract.setContractNumber("HT"+CodeGenerator.generateContractNumber());//合同编号
        contract.setElderName(elder.getName());//老人姓名
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());//合同开始时间
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());//合同结束时间
        int status = LocalDateTime.now().isBefore(contract.getStartDate())?0:LocalDateTime.now().isBefore(contract.getEndDate())?1:2;//合同的状态
        contract.setStatus(status);
        boolean resultContract = contractService.save(contract);
        if (!resultContract){
            throw new RuntimeException("新增合同失败");
        }


        //6.新增入住信息
        CheckIn checkIn = new CheckIn();
        //拷贝
        BeanUtils.copyProperties(dto.getCheckInConfigDto(),checkIn);
        checkIn.setElderName(elder.getName());//老人姓名
        checkIn.setElderId(elder.getId());//老人id
        checkIn.setIdCardNo(cardNumber);//老人身份证号
        checkIn.setBedNumber(bed.getBedNumber());//床位编号
        checkIn.setStatus(0);//已入住
        checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));//家属信息的JSON字符串
        boolean resultCheckIn = checkInService.save(checkIn);
        if (!resultCheckIn){
            throw new RuntimeException("新增入住失败");
        }

        //7.新增入住配置
        CheckInConfig checkInConfig = new CheckInConfig();
        //拷贝
        BeanUtils.copyProperties(dto.getCheckInConfigDto(),checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());//入住信息id，只用保存这一个，其他的都有了
        boolean resultCheckInConfig = checkInConfigService.save(checkInConfig);
        if (!resultCheckInConfig){
            throw new RuntimeException("新增入住配置信息失败");
        }
    }


    /**
     * 查询入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();//用于返回
        //查询入住信息
        CheckIn checkIn = this.selectCheckInById(id);
        //查询老人信息
        Elder elder = elderService.selectElderById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder,checkInElderVo);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        //查询签约办理
        Contract contract = contractService.lambdaQuery().eq(Contract::getElderId,checkIn.getElderId()).one();
        checkInDetailVo.setContract(contract);
        //查询入住配置
        CheckInConfig checkInConfig = checkInConfigService.lambdaQuery().eq(CheckInConfig::getCheckInId, id).one();
        if (checkInConfig != null) {
            CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
            BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
            checkInConfigVo.setStartDate(checkIn.getStartDate());
            checkInConfigVo.setEndDate(checkIn.getEndDate());
            checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        }
        //转换家属列表
        String sanitizizedJson = checkIn.getRemark();
        if (!checkIn.getRemark().startsWith("[")){
            sanitizizedJson = "[{\"name\" : \"\"} ]";
        }
        List<ElderFamilyVo> elderFamilyVos = JSON.parseArray(sanitizizedJson,ElderFamilyVo.class);
        //整合数据返回（CheckInDetailVo）
        checkInDetailVo.setElderFamilyVoList(elderFamilyVos);

        return checkInDetailVo;
    }
}
